package com.example.config;


import com.example.websocket.handler.RegisterWebSocketHandler;
import com.example.websocket.util.SpringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistration;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.util.Comparator;
import java.util.Map;


/**
 * @author dot_seven
 */
@Configuration
@EnableWebSocket
@DependsOn("springUtils")
@ConditionalOnProperty(prefix = "websocket", name = "enable", havingValue = "true")
public class WsConfig implements WebSocketConfigurer {

    /**
     * @param webSocketHandlerRegistry
     */
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        Map<String, RegisterWebSocketHandler> beans = SpringUtils.getBeans(RegisterWebSocketHandler.class);
        if (!CollectionUtils.isEmpty(beans)) {
            beans.values()
                    .stream()
                    .sorted(Comparator.comparing(RegisterWebSocketHandler::order))
                    .forEach(ele->{
                        WebSocketHandlerRegistration registration = webSocketHandlerRegistry.addHandler(ele, ele.paths());
                        HandshakeInterceptor[] interceptors = ele.interceptors();
                        if (ArrayUtils.isNotEmpty(interceptors)) {
                            registration.addInterceptors(interceptors);
                        }
                        HandshakeHandler handshakeHandler = ele.handshakeHandler();
                        if (handshakeHandler!=null) {
                            registration.setHandshakeHandler(handshakeHandler);
                        }
                        String[] allowedOrigins = ele.allowedOrigins();
                        if (ArrayUtils.isNotEmpty(allowedOrigins)) {
                            registration.setAllowedOrigins(allowedOrigins);
                        }
                    });
        }
    }

    /**
     * 支持websocket de注解
     * */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}
